#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define FILENAME   "stud"
#define NEWFILENAME   "stud_sort"
#define STUDENTNUM 5

enum Sex {MALE, FEMALE};

struct student {
    int id;
    char name[40];
    enum Sex sex;
    float chinese_socre;
    float math_score;
    float english_score;
    float avg_score;
};

// 打印数据
void printInfo(struct student* students) {
    for (int i = 0; i < STUDENTNUM; i++) {
        char* gender;
        gender = students[i].sex == FEMALE ? "女" : "男";
        printf("%d %s %s %f %f %f %f\n", 
            students[i].id,
            students[i].name,
            gender,
            students[i].chinese_socre,
            students[i].english_score,
            students[i].math_score,
            students[i].avg_score);
    }
}

// 获取数据
void getInfo(struct student* students) {
    for (int i = 0; i < STUDENTNUM; i++) {
        printf("请输入第%d个学生的信息\n", i + 1);
        printf("请输入学号:");
        scanf("%d", &students[i].id);
        printf("请输入姓名:");
        scanf("%s", students[i].name);
        printf("请输入性别(男 女):");
        char gender[10];
        scanf("%s", gender);
        
        if (strcmp(gender, "男") == 0)
            students[i].sex = MALE;
        else if (strcmp(gender, "女") == 0)
            students[i].sex = FEMALE;
        else {
            printf("输入错误...");
            exit(1);
        }
        float chinese, math, english, avg;
        printf("请输入学生的语文、数学、英语成绩:");
        scanf("%f %f %f", &chinese, &math, &english);
        avg = (chinese + math + english) / 3;
        students[i].chinese_socre = chinese;
        students[i].english_score = english;
        students[i].math_score = math;
        students[i].avg_score = avg;
    }
}

// 写入文件
void writeInfo(struct student* students, const char* filename) {
    FILE* fp = fopen(filename, "w");
    if (fp == NULL) {
        perror("写文件失败");
        exit(1);
    }
    for (int i = 0; i < STUDENTNUM; i++) {
        fprintf(fp, "%d %s %d %f %f %f %f\n", 
            students[i].id,
            students[i].name,
            students[i].sex,
            students[i].chinese_socre,
            students[i].english_score,
            students[i].math_score,
            students[i].avg_score);
    }
    fclose(fp);
}


int main() {
    struct student students[STUDENTNUM];

    getInfo(students);
    // 查看获取的数据
    printInfo(students);
    writeInfo(students, FILENAME);
    return 0;
}
